/**
 * 获取链表倒数第N个元素。
 */
public class JavaDemo17 {
    public static void main(String[] args) {

        ListNode head = new ListNode(0);
        ListNode next = head;
        for (int i = 1; i < 10; i++) {
            ListNode node = new ListNode(i);
            next.next = node;
            next = node;
        }
        ListNode showParent = head;
        while (showParent != null) {
            System.out.println(showParent.val);
            showParent = showParent.next;
        }
        System.out.println("---------------");
        showParent = getReciprocalNode(head,2);
        while (showParent != null) {
            System.out.println(showParent.val);
            showParent = showParent.next;
        }
    }

    private static ListNode getReciprocalNode(ListNode head, int n) {
        int length=0;
        ListNode cur=head;
        while (cur!=null){
            cur=cur.next;
            length++;
        }
        cur=head;
        for (int i=0;i<length-n;i++){
            cur=cur.next;
        }
        return cur;
    }

}
